<?php

namespace app\admin\controller;

use app\api\model\User;
use think\Db;
use app\api\model\Privatechat;

class Proxy extends Common
{
    public function lists()
    {
        $where = ['proxy' => 1];

        $start = input('start');
        $end = input('end');

        $topup_where = [];
        $order_where = [];
        if ($start && $end) {
            $topup_where['addtime'] = ['between', [date('Y-m-d H:i:s', strtotime($start)), date('Y-m-d H:i:s', strtotime($end))]];
            $order_where['update_time'] = ['between', [strtotime($start), strtotime($end)]];
        } else if ($start && !$end) {
            $topup_where['addtime'] = ['egt', date('Y-m-d H:i:s', strtotime($start))];
            $order_where['update_time'] = ['egt', (strtotime($start))];
        } else if (!$start && $end) {
            $topup_where['addtime'] = ['elt', date('Y-m-d H:i:s', strtotime($end))];
            $order_where['update_time'] = ['elt', strtotime($end)];
        }


        $search = input('search') ?: 'topup';
        $order_search = input('order') ?: 'order';

        $order = $search . ' ' . $order_search;

        $order .= ',id desc';

        $data = Db::name('user')->where($where)->select();

        $contain = [];
        foreach ($data as $key => $item) {
            $users = Db::name("user")->field('id, register_datetime')->where(["yqr" => $item["yqm"]])->select();

            if ($users) {
                $ids = array_column($users, 'id');

                $count = Db::name("order_common")->where(['user_id' => ["in", $ids], 'status' => 1, 'pays' => ['neq', 1]])->group('user_id')->count();

                $topup = Db::name("topup")->where(['fk_userid' => ["in", $ids], 'state' => 1])->sum("money");

                $topup_where['fk_userid'] = ["in", $ids];
                $topup_where['state'] = 1;
                if (isset($topup_where['addtime'])) {
                    $new_topup = Db::name("topup")->where($topup_where)->sum("money");
                } else {
                    $new_topup = Db::name("topup")->where($topup_where)->whereTime('addtime', 'd')->sum("money");
                }

                $order_where['user_id'] = ["in", $ids];
                $order_where['status'] = 1;
                $order_where['pays'] = ["neq", 1];
                if (isset($order_where['update_time'])) {
                    $new_cost_user = Db::name("order_common")->where($order_where)->order('id desc')->group('user_id')->count();
                } else {
                    $new_cost_user = Db::name("order_common")->where($order_where)->whereTime('update_time', 'd')->order('id desc')->group('user_id')->count();
                }
            } else {
                $count = 0;
                $topup = 0;
                $new_topup = 0;
                $new_cost_user = 0;
                $ids = [];
            }

            $new_user = 0;
            foreach ($users as $m => $n) {
                if ($start && $end) {
                    if (strtotime($n['register_datetime']) >= strtotime($start) && strtotime($n['register_datetime']) <= (strtotime($end) + 86400)) {
                        $new_user++;
                    }
                } else if ($start && !$end) {
                    if (strtotime($n['register_datetime']) >= strtotime($start)) {
                        $new_user++;
                    }
                } else if (!$start && $end) {
                    if (strtotime($n['register_datetime']) <= (strtotime($end) + 86400)) {
                        $new_user++;
                    }
                } else {
                    if (strtotime($n['register_datetime']) >= strtotime(date('Ymd'))) {
                        $new_user++;
                    }
                }
            }

            $contain[] = [
                'id' => $item['id'],
                'sum_user' => count($ids),
                'cost_user' => $count,
                'new_user' => $new_user,
                'topup' => $topup,
                'new_topup' => $new_topup,
                'new_cost_user' => $new_cost_user,
            ];
        }

        if ($contain) {
            (new User)->saveAll($contain);
        }

        $data = Db::name('user')->where($where)->order($order)->paginate(_getCachePages(), false, ['query' => request()->param()]);

        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);

        $this->assign('search', $search);
        $this->assign('order', $order_search);

        if ($start) {
            $this->assign('start', $start);
        }

        if ($end) {
            $this->assign('end', $end);
        }

        return $this->fetch();
    }

    public function add()
    {
        $id = input('id');

        if (request()->isAjax()) {

            $post = input('post.');

            if (isset($post['fencheng_vip'])) {
                $post['fencheng_vip'] = $post['fencheng_vip'] / 100;
            }

            if (isset($post['fencheng_topup'])) {
                $post['fencheng_topup'] = $post['fencheng_topup'] / 100;
            }

            if (isset($post['fencheng_chat'])) {
                $post['fencheng_chat'] = $post['fencheng_chat'] / 100;
            }

            if (!$id) {
                if (!$post['name']) {
                    return ['err' => '请填写账号'];
                }
                if (!$post['password']) {
                    return ['err' => '请填写密码'];
                }

                $user = Db::name('user')->where(['name' => $post['name'], 'proxy' => 1])->find();
                if ($user) {
                    return ['err' => '账号已存在'];
                }

                //生成唯一邀请码
                for ($i = 2; $i > 1; $i++) {
                    $code = code();

                    $test = Db::name('user')->where('yqm', $code)->select();
                    if (!$test) {
                        $i = 0;
                    }
                }


                $post['yqm'] = $code;
                $post['proxy'] = 1;

                $result = Db::name('user')->insert($post);

                $data = $result ? ['ret' => '添加成功'] : ['err' => '添加失败'];
            } else {

                if (isset($post['password']) && !$post['password']) {
                    unset($post['password']);
                }

                if ($post['name']) {
                    $user = Db::name('user')->where(['name' => $post['name'], 'id' => ['neq', $id]])->find();
                    if ($user) {
                        return ['err' => '账号已存在'];
                    }
                }

                $db = Db::name('user')->where('id', $id)->update($post);
                if ($db !== false) {
                    $data = ['ret' => '修改成功'];
                } else {
                    $data = ['err' => '修改失败'];
                }
            }
        } else {
            if ($id) {
                $name = Db::name('user')->find($id);

                if ($name) {
                    $this->assign('name', $name);
                } else {
                    $data = ['err' => 'id参数错误'];
                }
            }

            $data = $this->fetch();
        }
        return $data;
    }
    
    public function join()
    {
        $where = [];
        
        $status = input('status');
        if ($status !== null) {
            $where['t1.status'] = $status;
        } else {
            $where['t1.status'] = 1;
        }

        
        $search_name = input('param.name');
        $search_type = input('param.search');
        if ($search_name && $search_type) {
            $where['t2.' . $search_type] = $search_name;
        }
        
        $data = Db::name('proxy_auth t1')
            ->field('t1.*, t2.name username,t2.phone userphone')
            ->join('user t2', 't2.id = t1.user_id')
            ->where($where)->order('t1.id desc')
            ->paginate(_getCachePages(), false, ['query' => request()->param()]);
        
        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);

        $this->assign('status', $status);
        
        return $this->fetch();
    }
    
    public function authEdit()
    {
        $id = input('id');
        
        if (request()->isAjax()) {
            
            $post = input('post.');
            
            if ($id) {
                $auth = Db::name('proxy_auth')->find($id);
                
                $result = Db::name('proxy_auth')->where('id', $id)->update(['status' => $post['status'], 'reason' => input('reason'), 'update_time' => time()]);
                
                
                if (in_array($post['status'], [-1,1])) {
                    if ($post['status'] == -1) {
                        $content = '代理申请未通过，请重新提交。原因:' . input('reason');
                    } else {
                        Db::name('user')->where(['id' => $auth['user_id']])->update(['proxy' => 1]);
                        
                        $content = '你的代理申请已通过。';
                    }
                    
                    Privatechat::notice($auth['user_id'], $content);
                }
                
                $data = $result ? ['ret' => '修改成功'] : ['err' => '修改失败'];
            } else {
                $data = ["err" => '参数缺失'];
            }
        }
        return $data;
    }
    
    public function authDel()
    {
        if (request()->isAjax()) {
            
            $id = input('id');
            if ($id) {
                $db = Db::name('proxy_auth')->delete($id);
                if ($db) {
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }
}